var Views = Views || {};
Views.SurveyItem = Backbone.View.extend({
  viewClassName: 'SurveyItem',
  className: 'list',
  defaults: {
    templateId: '#survey-card-item'
  },
  initialize: function(options) {

    var opts = _.extend({}, this.defaults, options);
    this._templateId = opts.templateId;	 
    this._parent = opts.parent;
	
  },
  events: {
    'click .publish': 'publishSurvey',
    'click .switch>div': 'toggleVisibility'
  },
  render: function() {

    var template = _.template($(this._templateId).html());
    var data = this.model ? this.model.toJSON() : {};
    var html = template(data);
    this.$el.html(html);
    return this;
  },

  publishSurvey: function(e) {
    var $target = $(e.target);
    if ($target.hasClass('loading')) return;

    $target.addClass('loading');
    var self = this;
    var published = this.model.get('published');
    $.post('/survey/publish.do', {event_id: this.model.get('event_id'), survey_id: this.model.get('id'), publish: published ? 0 : 1}, function(result) {
      $target.removeClass('loading');
      if (result.status == 1) {
        self.model.set('published', published ? 0 : 1);
        if (self.model.get('type') == 3) self.model.set('first_step', true);
        // check start/end
        var start_time = self.model.get('start_time'),
          end_time = self.model.get('end_time'),
          curTime = new Date().getTime(),
          survey_status = 2;
        if (start_time) {
          start_time = new Date(start_time).getTime();
        }
        if (end_time) {
          end_time = new Date(end_time).getTime();
        }
        if (start_time > curTime) { // not start
          survey_status = 2;
        } else if (start_time <= curTime && end_time > curTime) {
          survey_status = 3;
        } else if (end_time <= curTime) {
          survey_status = 4;
        }
        self.model.set('survey_status', survey_status);
        self.render();
      } else {
        if (result.status == 4) {
          alert('未设置题目的问卷不可发布，请点击设计问卷按钮完善您的问卷');
        } else {
          alert(result.msg);
        }
      }
    });
  },

  toggleVisibility: function(e) {
    var $target = $(e.target);
    if ($target.closest('.switch').hasClass('loading')) return;

    $target.closest('.switch').addClass('loading');

    var self = this;
    var visibility = this.model.get('visibility');
    $.post('/survey/visibility.do',{event_id: this.model.get('event_id'), survey_id: this.model.get('id'), visibility: visibility ? 0 : 1}, function(result) {
      $target.closest('.switch').removeClass('loading');
      if (result.status == 1) {
    	
        self.model.set('visibility', visibility ? 0 : 1);
        self.render();
      } else {
        alert(result.msg);
      }
    });
  }
});

Views.SurveyPagination = Backbone.View.extend({
  viewClassName: 'SurveyPagination',
  defaults: {
    templateId: '#survey-pagination',
    pagelen: 5, // show 5 buttons
    each: 10, // number of the page
    total: 0, // number of items
    page: 1 // current page number
    //pages: 1 // all pages number
  },
  events: {
    'click dl a': 'changePage'
  },
  initialize: function(options) {
    var opts = _.extend({}, this.defaults, options);

    this._fetching = false;

    this._parent = opts.parent;

    this._pagelen = opts.pagelen;
    this._each = opts.each;
    this._total = opts.total;

    this._init = 1;
    this._max = 1;
    this._pageOffset = (this._pagelen - 1) / 2;

    this._page = opts.page > this._pages ? this._pages : (opts.page < 0) ? 1 : opts.page;
    this._max = this._pages = Math.ceil(this._total / 10);

    this._handleResources();
	console.log(12215);
  },

  _handleResources: function() {
    if (this._pages > this._pagelen) {
      if (this._page <= this._pageOffset) {
        this._init = 1;
        this._max = this._pagelen;
      } else {
        if (this._page + this._pageOffset >= this._pages + 1) {
          this._init = this._pages - this._pagelen + 1;
        } else {
          this._init = this._page - this._pageOffset;
          this._max = this._page + this._pageOffset;
        }
      }
    }
  },

  render: function() {
	 
    var template = _.template($(this.defaults.templateId).html());
    var data = this.model ? this.model.toJSON() : {};
    data = _.extend({}, data, {
      page: this._page,
      init: this._init,
      max: this._max,
      total: this._total,
      pages: this._pages
    })
    var html = template(data);
    this.$el.html(html);

    return this;
  },

  changePage: function(evt) {
	  
    var $target = $(evt.currentTarget);
    if ($target.hasClass('disabled') || this._fetching) {
      console.log('fetching data...');
      return;
    }

    this.$('dl a').addClass('disabled');

    var tag = $target.data('tag');
    switch(tag) {
      case 'F':
        this._page = 1;
        break;
      case 'L':
        this._page = this._pages;
        break;
      case 'N':
        if (this._page + 1 <= this._pages) {
          this._page++;
        } else {
          this._page = this._pages;
        }
        break;
      case 'P':
        if (this._page - 1 >= 1) {
          this._page--;
        } else {
          this._page = 1;
        }
        break;
      default:
        var page = parseInt(tag, 10);
        if (this._page == page) {
          console.log('page not changed');
          this.$('dl a').removeClass('disabled');
          return;
        }
        if (!isNaN(page)) {
          this._page = page;
        }
    }

    this._parent.trigger('pageChange', this._page - 1);

    this._fetching = true;

    this._handleResources();
    this.render();
  }
});

Views.SurveyList = Backbone.View.extend({
  viewClassName: 'SurveyList',
  defaults: {
    container: '.manage_main',
    paginationContainer: '.test_formBody'
  },
  initialize: function(options) {
    var opts = _.extend({}, this.defaults, options);
    this.$container = $(opts.container);
    this.$paginationContainer = $(opts.paginationContainer);

    this.listenTo(this.collection, 'sync', this.render);

    this.bind('pageChange', this.pageChange);
  },
  events: {

  },
  render: function() {
    var self = this;
    $('.loading, .none', this.$container).hide();
    if (this.collection && this.collection.length > 0) {
      var fragment = document.createDocumentFragment();
      this.collection.each(function(model) {
        self.renderItem(model, fragment);
      });

      this.$container.html(fragment);

      var paginationView = new Views.SurveyPagination({
        parent: this,
        total: this.collection.total,
        page: this.collection.page ? 1 + this.collection.page : 1
      });
      this.$paginationContainer.html(paginationView.render().el);
    } else {
      if (this.collection.login == 0) {
        $('#btnAddSurvey').hide();
        $('.none', this.$container).html('暂无数据').show();
      } else {
        $('.loading', this.$container).hide();
        $('.none', this.$container).show();
      }
    }

    return this;
  },

  renderItem: function(model, fragment) {
    var view = new Views.SurveyItem({
      model: model,
      parent: this
    });

    view.render();
    fragment.appendChild(view.el);
  },

  pageChange: function(page) {
    this.$container.html('<div class="loading" style="text-align: center;">加载中...</div>');
    
    //document.body.scrollTop = 0;
    $('body').animate({
      scrollTop: 0
    }, 500);

    this.collection.getList(null, page);
  }
});

window.survey_list = {};
$(document).ready(function() {
  var event_id = getQueryString("event_id");
  $('#btnAddSurvey').attr('href', $('#btnAddSurvey').attr('href') + event_id);

  var surveyList = new SurveyList();
  surveyList.fetched = false;
  var view = new Views.SurveyList({
    collection: surveyList,
    container: '.manage_main'
  });
    // add by mingjie 2016-04-05
	var access = checkBusinessUseRole();
	if(access == 1){
		surveyList.getList(event_id);
	}else if(access == 'cache'){
		$(".rightBody").html(template_unAuthorized);
		$("#authorizedType").html('活动问卷');
		$("#btnAddSurvey").hide();
		$("#applyNow").attr("href","javascript:void(0);");
		$("#applyNow").attr("class","btn_small btn_go");
		$("#applyNow").html("已申请");
		$("#mainBox").addClass("noOpr");
		$("#tips").html("您的申请已提交！我们将于两小时内审核并与您联系 ，如有问题可拨打客服电话。");
	}else{
		$(".rightBody").html(template_unAuthorized);
		$("#authorizedType").html('活动问卷');
		$("#btnAddSurvey").hide();
	}
  


  $('.manage_survey').on('click', '.actions .view', function(e) {
    //alert('preview the survey, id=' + $(this).data('survey-id'));
    alert('Implementing...');
  }).on('click', '.actions .edit', function(e) {
    //alert('editing the survey, id=' + $(this).data('survey-id'));
  }).on('click', 'ul .delete', function(e) {
    var self = this;
    if ($(this).hasClass('loading')) return;

    var survey_id = $(this).data('survey-id');
    if (confirm('您确定删除此问卷么？')) {
      $(this).addClass('loading');
      $.post('/survey/delete.do', {'survey_id': survey_id, 'event_id': event_id}, function(result){
        if (result && result.status == 1) {
          // remove the row
          $(self).closest('.list').hide('slide', {direction: 'right'}, 1000, function() {
            $(self).closest('.list').remove();
            if ($('.manage_main .list').length == 0) {
              $('.no-data').show();
            }
          });
        } else {
          $(self).removeClass('loading');
          alert('删除失败');
        }
      });
    }
  }).on('click', '.setting a', function(e) {
    //UIdialogNew($(e.target));
  }).on('click', 'ul .copy', function(e) {
//    alert('Implementing...');
//    return;
    var survey_id = $(this).data('survey-id');
    if ($(this).attr("disable") == "yes") { alert('正在复制中~');return false; }
    $(this).attr("disable","yes");
    if (survey_id) {
      $.get('/survey/copy.do', {survey_id: survey_id, event_id: event_id}, function(result) {
        if (result && result.status == 1) {
          alert('复制成功');
          location.href = '/html/page/survey/create.html?event_id=' + event_id + '&survey_id=' + result.data.id;
        }
      });
    }
  });
});
